<template>
  <mavon-editor
    ref="md"
    v-model="content"
    @input="$emit('input', content)"
    @imgAdd="imgAdd"
    @change="change"
    :ishljs="true"
    style="min-height: 600px"
  />
</template>

<script>
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import COS from "cos-js-sdk-v5";
import axios from "axios";

export default {
  components: {
    mavonEditor,
  },
  data: function () {
    return {
      content: this.msg,
    };
  },
  props: {
    msg: String,
  },
  methods: {
    imgAdd(pos, file) {
      let m_this = this;
      let result = Object;
      axios.post("/api/COS/getToken?name=" + file.name).then((data) => {
        result = data.data;
        var cos = new COS({
          // 必选参数
          getAuthorization: function (options, callback) {
            callback({
              TmpSecretId: result.Credentials.TmpSecretId,
              TmpSecretKey: result.Credentials.TmpSecretKey,
              XCosSecurityToken: result.Credentials.Token,
              StartTime: result.StartTime, // 时间戳，单位秒，如：1580000000
              ExpiredTime: result.ExpiredTime, // 时间戳，单位秒，如：1580000900
            });
          },
        });
        cos.putObject(
          {
            Bucket: "myblog-1302916147" /* 必须 */,
            Region: "ap-guangzhou" /* 存储桶所在地域，必须字段 */,
            Key: result.Time + "/" + result.Name /* 必须 */,
            StorageClass: "STANDARD",
            Body: file, // 上传文件对象
            onProgress: function (progressData) {
              console.log(JSON.stringify(progressData));
            },
          },
          function (err, data) {
            /**
             * $vm 指为mavonEditor实例，可以通过如下两种方式获取
             * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
             * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
             */
            m_this.$refs.md.$img2Url(pos, "https://" + data.Location);
          }
        );
      });
    },
    // 所有操作都会被解析重新渲染
    change(value, render) {
      // render 为 markdown 解析后的结果[html]
      // this.blog.Content = render;
      // console.log(value);
    },
  },
};
</script>